<template>
    <topBar>
        <template v-slot:left>
            <div class="tools-box" v-if="!isSettingPage && isLogin">
                <el-popover
                    trigger="click"
                    ref="addPopoverRef"
                    placement="bottom-start"
                    width="364"
                    popper-class="created-popover">
                    <div class="add-type-box">
                        <el-scrollbar max-height="calc(100vh - 120px)">
                            <template v-for="(item,index) in addFileList" :key="index">
                                <div class="add-type-title">{{ $t(item.title) }}</div>
                                <div class="type-lists">
                                    <div class="type-item" v-for="(lItem,lIndex) in item.list" :key="lIndex"
                                         @click="createFile(lItem,lIndex)" :id="`type-item-${lIndex}`"
                                         :disabled="!!checkedFileItem.type && !$permissionRole('document_add',checkedFileItem.dcIdentifying) && lItem.type!='knowledge'"
                                         :class="[(!!checkedFileItem.type && !$permissionRole('document_add',checkedFileItem.dcIdentifying) && lItem.type!='knowledge') &&'disabled-click']">
                                        <svg class="type-icon">
                                            <use v-bind:xlink:href="`#${lItem.icon}`"></use>
                                        </svg>
                                        <div class="type-name">
                                            {{ $t(lItem.label) }}
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </el-scrollbar>
                    </div>
                    <template #reference>
                        <!-- popClick -->
                        <el-button type="primary" class="">
                            <svg class="icon">
                                <use xlink:href="#keowledge-xinjian"></use>
                            </svg>
                            {{ $t('message.buttons.new') }}
                        </el-button>
                    </template>
                </el-popover>
                <el-popover trigger="click"
                            ref="importPopoverRef"
                            placement="bottom-start"
                            width="176"
                            popper-class="import-popover">
                    <div class="import-item" @click.stop="openUpload('file')"
                         :class="[(!!checkedFileItem.type && !$permissionRole('document_add',checkedFileItem.dcIdentifying)) &&'disabled-click']">
                        <div class="upload-button">
                            <svg class="icon">
                                <use xlink:href="#keowledge-daoruwendang"></use>
                            </svg>
                            <span>{{ $t('message.text.importFile') }}</span>
                        </div>
                    </div>
                    <div class="import-item" @click.stop="openUpload('folder')"
                         :class="[(!!checkedFileItem.type && !$permissionRole('document_add',checkedFileItem.dcIdentifying)) &&'disabled-click']">
                        <svg class="icon">
                            <use xlink:href="#keowledge-daoruwenjianjia"></use>
                        </svg>
                        <span>{{ $t('message.text.importFolder') }}</span>
                    </div>
                    <template #reference>
                        <el-button class="import-button">
                            <svg class="icon">
                                <use xlink:href="#keowledge-daoru"></use>
                            </svg>
                            {{ $t('message.buttons.import') }}
                        </el-button>
                    </template>
                </el-popover>
                <el-button type="text" @click="openSynchronism" class="hover-back"
                           :style="{width:locale!='zh-CN'?'110px':''}">
                    <i class="knowledge-iconfont icon keowledge-wendangtongbu"></i>
                    {{ $t('message.buttons.docSync') }}
                </el-button>
            </div>
            <div class="setting-box" v-if="isSettingPage">
                <svg class="home-icon" @click="goHome()">
                    <use xlink:href="#keowledge-shouye-weixuanzhong"></use>
                </svg>
                <div class="line"></div>
                <div class="bread-item" v-for="(item,index) in breadList" :key="index"
                     :class="[index==(breadList.length-1) && 'bread-item-active']">
                    <svg class="bread-icon" v-if="index!=0">
                        <use xlink:href="#keowledge-a-zu4701"></use>
                    </svg>
                    <span>{{ $t(item) }}</span>
                </div>
            </div>
        </template>
    </topBar>
    <div class="common-body" :class="[getBgClass]">
        <el-scrollbar class="common-scrollbar">
            <router-view></router-view>
        </el-scrollbar>
    </div>
    <selectKnow ref="selectKnowRef" :title="selectKnowTitle" @callBack="getCheckedFile"></selectKnow>
    <knowledgeInfo ref="knowledgeInfoRef"></knowledgeInfo>
    <uploadBox ref="commonUploadBoxRef"></uploadBox>
    <createFolder ref="createFolderRef" @createSuccess="createSuccess"></createFolder>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    watch,
    onMounted,
    computed,
    nextTick,
    getCurrentInstance,
    onBeforeUnmount
} from 'vue'
import topBar from '@/views/topBar/topBar.vue'
import selectKnow from '@/views/selectKnow/index.vue'
import knowledgeInfo from '@/views/knowledgeInfo/index.vue'
import {useRouter, useRoute} from "vue-router"
import type {checkedKnow, uploadFile} from '@/types/common'
// import { uploadByPieces } from "@/utils/uploadFile";
import useCommonStore from '@/store/common.js'
import uploadBox from '@/views/common/uploadBox.vue'
import createFolder from '@/views/common/createFolder.vue'
import {addLibrary} from '@/api/knowledge'
import {createOnlyOfficeFile} from '@/api/common'
import {isOffice} from '@/utils/util'
import useKnowledgeStore from '@/store/knowledge.js'
import {$permissionRole} from '@/utils/role'
import * as O from '@/utils/uniqueId'
import useUserInfoStore from '@/store/userInfo';
import {useHookI18n} from '@/hooks/i18n'

const {locale, $t} = useHookI18n()
const knowStore = useKnowledgeStore()
const router = useRouter();
const route = useRoute()
const emit = defineEmits([""])
// const props = defineProps({})
const {proxy} = getCurrentInstance() as any
const addPopoverRef = ref()
const importPopoverRef = ref()
// const fileUploadRef = ref()
// const folderUploadRef = ref()
// const fileUploadButtonRef = ref()
const selectKnowRef = ref()
const knowledgeInfoRef = ref()
const selectKnowTitle = ref('')
const uploadFileType = ref('')
// const uploadFileList = ref<uploadFile[]>([])
// const uploadBindKeyObj = ref<{start:number| undefined,end:number| undefined}>({})
// const bindFileNum = ref(0)
// const bindFileList = ref<any[]>([])
const checkedFileItem = ref<checkedKnow>({
    id: '',
    name: '',
    orderId: 0,
    parentId: '',
    dcIdentifying: [],
    type: ''
})
// const uploadFileLimit = pluginConfig.uploadFileLimit || 5
const addFileList = reactive([
    {
        title: 'message.text.generalDocument',
        list: [
            {
                label: 'message.text.textDocument',
                type: "document_html",
                icon: 'keowledge-a-zu3554'
            },
            {
                label: 'message.text.formDocument',
                type: "document_xlsx",
                icon: 'keowledge-a-zu3555'
            },
            {
                label: 'message.text.mindMapDoc',
                type: "document_map",
                icon: 'keowledge-naotu'
            }, {
                label: 'message.text.processDoc',
                type: "document_flow",
                icon: 'keowledge-liucheng'
            }, {
                label: 'message.text.markDown',
                type: "md",
                icon: 'keowledge-MAK'
            }, {
                label: 'message.text.xmind',
                type: "xmind",
                icon: 'keowledge-xmind'
            }, {
                label: 'message.text.urlDocument',
                type: "url_address",
                icon: 'keowledge-URL'
            }
        ],
    }, {
        title: 'message.text.officeSuite',
        list: [{
            label: 'message.text.word',
            type: "office_doc",
            icon: 'keowledge-a-zu3558'
        }, {
            label: 'message.text.excel',
            type: "office_xlsx",
            icon: 'keowledge-excel'
        }, {
            label: 'message.text.ppt',
            type: "office_ppt",
            icon: 'keowledge-a-zu3556'
        }, {
            label: 'message.text.csv',
            type: "office_csv",
            icon: 'keowledge-CVS'
        }]
    }, {
        title: 'message.text.more',
        list: [{
            label: 'message.text.library',
            type: "knowledge",
            icon: 'keowledge-xinjianwenku'
        }, {
            label: 'message.text.addNewFolder',
            type: "add_directory",
            icon: 'keowledge-wenjian'
        }, {
            label: 'message.text.templateCenter',
            type: "more_template",
            icon: 'keowledge-gengduomoban'
        }]
    }
])
const createFolderRef = ref()
onMounted(() => {
    proxy.$eventBus.$on('breadListChange', breadListChange)
    proxy.$eventBus.$on('changeCheckFile', setCheckFile)
    proxy.$eventBus.$on('openFolder', openFolder)
    proxy.$eventBus.$on("uploadFile", uploadFile)
    proxy.$eventBus.$on("createKnowFile", createKnowFile)
    proxy.$eventBus.$on("createKnow", createKnow)
})
onBeforeUnmount(() => {
    proxy.$eventBus.$off('breadListChange', breadListChange)
    proxy.$eventBus.$off('changeCheckFile', setCheckFile)
    proxy.$eventBus.$off('openFolder', openFolder)
    proxy.$eventBus.$off("uploadFile", uploadFile)
    proxy.$eventBus.$off("createKnowFile", createKnowFile)
    proxy.$eventBus.$off("createKnow", createKnow)
})
const userStore = useUserInfoStore()
const isLogin = computed(() => {
    return !!userStore.access_token
})
const commonStore = useCommonStore()
const getBgClass = computed(() => {
    let str = ''
    if (route.path.indexOf('/setting/control') != -1) {
        str = 'setting-body'
    }
    return str
})
const isSettingPage = computed(() => {
    let str = false
    if (route.path.indexOf('/setting') != -1) {
        str = true
    }
    return str
})
const breadOther = ref<any[]>([])
const addMessage = ref('')
const breadList = computed(() => {
    let arr = []
    arr.push($t(route.meta.lang as string), ...breadOther.value)
    return arr
})
const commonUploadBoxRef = ref()
const officeTypeObj = {
    'office_doc': 'docx',
    'office_xlsx': 'xlsx',
    'office_ppt': 'pptx',
    'office_pdf': 'pdf',
    'office_csv': 'csv',
}
watch(() => route.params, () => {
    breadOther.value = []
})

function breadListChange(val: any) {
    breadOther.value = [val]
}

function setCheckFile(val: checkedKnow) {
    checkedFileItem.value = val
}

// 创建文件夹
function openFolder(type: any, val: any) {
    if (event.target.getAttribute('disabled') == 'true') {
        return
    }
    publicCreateFile(type, val)
}

// 文库里面抛出的文件上传
function uploadFile(type: any, id: any) {
    commonUploadBoxRef.value.fileUpload(type, id)
}

// 创建文件的区分方法
function createFile(item: any, index: any) {
    if (eval(document.getElementById(`type-item-${index}`)!.getAttribute('disabled'))) {
        return
    }
    uploadFileType.value = item.type
    addMessage.value = $t(item.label)
    // popperRef
    if (route.params.id) {
        publicCreateFile(item.type, checkedFileItem.value)
    } else {
        switch (item.type) {
            case 'more_template':
                selectKnowTitle.value = $t('message.text.templateStorageLoaction')
                // 这里是打开选择文库的弹窗
                selectKnowRef.value.init()
                break;
            case 'add_directory':
                selectKnowTitle.value = $t('message.text.createNewFolder')
                // 这里是打开选择文库的弹窗
                selectKnowRef.value.init()
                break;
            case 'url_address':
            case 'document_html':
            case 'document_map':
            case 'document_xlsx':
            case 'document_flow':
            case 'md':
            case 'xmind':
            case 'office_doc':
            case 'office_xlsx':
            case 'office_ppt':
            case 'office_csv':
                selectKnowTitle.value = $t('message.buttons.new') + $t(item.label)
                // 这里是打开选择文库的弹窗
                selectKnowRef.value.init()
                break;
            default:
                knowledgeInfoRef.value?.init()
                break;
        }
    }
    addPopoverRef.value.hide()
}

function createKnow() {
    nextTick(() => {
        knowledgeInfoRef.value?.init()
    })
}

// 判定当前文件的类型是否可以编辑
function editType(item: any): string {
    let type = ''
    if (["document_map", "document_xlsx", "document_flow", "document_html", "md", 'xmind'].indexOf(item.type) > -1) {
        type = 'editor'
    } else if (['docx', 'xlsx', 'pptx', 'csv'].indexOf(item.nameSuffix) != -1) {
        type = 'office'
    } else {
        type = 'directory'
    }
    return type
}

// 创建成功后刷新目录树
function createSuccess(val: { id: string; knowledgeId: string }) {
    let editorType = editType(val)
    let knowledgeType: number = 0
    if (route.params.type == 'my') {
        knowledgeType = 1
    } else if (route.params.type == 'all') {
        knowledgeType = 0
    }
    knowStore.setBackPage({
        fromPage: route.path,
        docId: val.id,
        knowId: val.knowledgeId,
    }, O.uniqueId('-' + val.knowledgeId + '-' + val.id))
    if (editorType == 'editor') {
        proxy.$openUrl(`/#/editor?knowId=${val.knowledgeId}&docId=${val.id}&fromId=${knowledgeType}`, '_blank')
    } else if (editorType == 'office') {
        proxy.$openUrl(`/#/editorOffice?knowId=${val.knowledgeId}&docId=${val.id}&fromId=${knowledgeType}`, '_blank')
    }
    checkedFileItem.value = {
        id: '',
        name: '',
        orderId: 0,
        parentId: '',
        dcIdentifying: [],
        type: ''
    }
    proxy.$eventBus.$emit('refreshTree', val)
}

// 创建文档
function createKnowFile(type: any, data: any, mes: string) {
    addMessage.value = mes
    publicCreateFile(type, data)
}

// 公共创建文件
function publicCreateFile(type: any, data: any) {
    if (type != 'more_template') {
        checkedFileItem.value = data
    }
    switch (type) {
        case 'more_template':
            router.push({
                path: `/template`,
                query: {
                    parentId: ['directory', 'knowledge'].indexOf(data.type) != -1 ? data.id : data.parentId,
                    // parentName:data.name
                }
            })
            break
        case 'knowledge':
            knowledgeInfoRef.value?.init()
            break;
        case 'url_address':
        case 'add_directory':
            createFolderRef.value.init('add', data, type)
            break;
        case 'document_html':
        case 'document_map':
        case 'document_xlsx':
        case 'document_flow':
        case 'md':
        case 'xmind':
        case 'office_doc':
        case 'office_xlsx':
        case 'office_ppt':
        case 'office_csv':
            let fun = addLibrary
            if (isOffice(type)) {
                fun = createOnlyOfficeFile
            }
            fun({
                name: "未命名文件",
                id: data.knowledgeId || data.id,
                parentId: ['directory', 'knowledge'].indexOf(data.type) != -1 ? data.id : data.parentId,
                fileType: type,
                type: officeTypeObj[type as keyof typeof officeTypeObj],
                knowledgeId: data.knowledgeId || data.id,
            }).then(res => {
                if (res.data.code == 0) {
                    proxy.$onePrompt.$oneNotify({
                        title: $t('message.prompt'),
                        message: `${$t('message.text.create')}${addMessage.value}${$t('message.text.success')}`,
                        type: 'success',
                        position: 'bottom-right'
                    })
                    createSuccess(res.data.data)
                }
            })
            break;
        default:
            break;
    }
}

function openSynchronism() {
    proxy.$openSynchronism()
}

function openUpload(type: string) {
    if (!(!!checkedFileItem.value.type && !$permissionRole('document_add', checkedFileItem.value.dcIdentifying))) {
        uploadFileType.value = type
        if (route.params.id) {
            fileUpload()
        } else {
            selectKnowTitle.value = $t('message.text.fileImport')
            // 这里是打开选择文库的弹窗
            selectKnowRef.value.init()
        }
        importPopoverRef.value.hide()
    }
}

// 调用文件上传的事件，选择文件
function fileUpload() {
    commonUploadBoxRef.value.fileUpload(uploadFileType.value, ['knowledge', 'directory'].indexOf(checkedFileItem.value.type) == -1 ? checkedFileItem.value.parentId : checkedFileItem.value.id)
}

// 选好目录后回调
function getCheckedFile(item: { id: string; name: string; orderId?: number | undefined; parentId: string; knowledgeId?: string | undefined; dcLibraryId?: string | undefined; dcIdentifying?: Object[] | undefined; type: string }) {
    if (['file', 'folder'].indexOf(uploadFileType.value) != -1) {
        checkedFileItem.value = item
        fileUpload()
    } else {
        publicCreateFile(uploadFileType.value, item)
    }
}

function goHome() {
    router.push('/index')
}
</script>
<style lang="scss">
.top-bar-box {
    .tools-box {
        display: flex;
        align-items: center;
        position: relative;
        background-color: #fff;

        .upload-boxs {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 0px;
            overflow: hidden;
        }

        button {
            height: 36px;
            width: 96px;
        }

        .icon {
            width: 16px;
            height: 16px;
            margin-right: 4px;
        }

        .el-button--text {
            color: #363B4C;
            font-size: 14px;
            @include SourceHanSansCN-Regular
        }
    }

    .setting-box {
        display: flex;
        align-items: center;

        .home-icon {
            width: 14px;
            height: 14px;
            cursor: pointer;
        }

        .line {
            width: 1px;
            height: 8px;
            background: #D7D8DB;
            margin: 0px 8px;
        }

        .bread-item {
            font-size: 14px;
            color: #6F7588;
            @include SourceHanSansCN-Regular;
            display: flex;
            align-items: center;

            .bread-icon {
                width: 14px;
                height: 14px;
                margin: 0px 4px;
            }
        }

        .bread-item-active {
            color: #363B4C;

            span {
                @include SourceHanSansCN-Bold;
            }
        }
    }
}

.common-body {
    position: relative;
    height: calc(100% - 68px);

    .common-scrollbar > .el-scrollbar__wrap > .el-scrollbar__view {
        height: 100%;
    }

    // overflow: auto;
}

.setting-body {
    background-color: #F5F6F7;
}

.add-type-box {
    padding: 24px 0px;
    box-sizing: border-box;

    .add-type-title {
        font-size: 16px;
        color: #363B4C;
        @include SourceHanSansCN-Bold;
        margin-bottom: 12px;
        padding: 0px 20px;
        margin-top: 24px;
        box-sizing: border-box;

        &:nth-of-type(1) {
            margin-top: 0px;
        }
    }

    .type-lists {
        display: flex;
        flex-wrap: wrap;
        grid-column-gap: 6px;
        grid-row-gap: 12px;
        padding: 0px 20px;

        .type-item {
            cursor: pointer;
            border-radius: 6px;
            width: 76px;
            height: 76px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;

            &:hover {
                background: #F5F6F7;
            }

            .type-name {
                font-size: 14px;
                color: #363b4c;
                @include SourceHanSansCN-Regular;
                margin-top: 4px;
            }

            .type-icon {
                width: 36px;
                min-width: 36px;
                height: 36px;
                min-height: 36px;
            }
        }
    }
}

.created-popover {
    padding: 0px !important;
}

.import-popover {
    padding: 16px 8px !important;

    .import-item {
        display: flex;
        align-items: center;
        height: 36px;
        border-radius: 4px;
        cursor: pointer;
        padding: 0px 16px;
        box-sizing: border-box;
        @include SourceHanSansCN-Regular;
        font-size: 14px;
        color: #363B4C;
        position: relative;

        &:hover {
            background: #F5F6F7;
        }

        .folder-upload {
            position: absolute;
            z-index: 1;
            width: 100%;
            left: 0px;
        }

        .upload-button {
            color: #363B4C !important;
            display: flex;
            align-items: center;
        }

        .icon {
            width: 16px;
            height: 16px;
            margin-right: 8px;
        }
    }

    .disabled-click {
        .upload-button {
            color: #D7D8DB !important;
        }
    }
}

.import-button:active {
    border-color: transparent !important;
}
</style>